package com.yuzi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuzi.common.entity.UserInterfaceInfo;
import com.yuzi.project.exception.BusinessException;
import com.yuzi.project.mapper.UserInterfaceInfoMapper;
import com.yuzi.project.service.UserInterfaceInfoService;
import com.yuzi.project.common.ErrorCode;
import org.springframework.stereotype.Service;

/**
 * @author 29015
 * @description 针对表【user_interface_info(用户调用接口关系表)】的数据库操作Service实现
 * @createDate 2024-04-17 22:46:51
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {

    @Override
    public void voidUser_InterfaceInfo(UserInterfaceInfo user_interfaceInfo, boolean add) {
        if (user_interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer totalNum = user_interfaceInfo.getTotalNum();
        Long id = user_interfaceInfo.getId();
        Long userId = user_interfaceInfo.getUserId();
        if (totalNum > Math.pow(10, 8)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口数量过大");
        }
        if (add) {
            if (id <= 0 || userId <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或用户不存在");
            }
        }


    }

    /**
     * 调用次数+1
     *
     * @param userId
     * @param interfaceInfoId
     * @return
     */
    @Override
    public boolean invokeCount(long userId, long interfaceInfoId) {
        if (userId <= 0 || interfaceInfoId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UpdateWrapper<UserInterfaceInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("userId", userId);
        wrapper.eq("interfaceInfoId", interfaceInfoId);
        wrapper.gt("leftNum", 0);
        wrapper.setSql("totalNum = totalNum + 1,leftNum = leftNum - 1");
        return this.update(wrapper);
    }
}




